package zm.irc.message.processor;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import zm.irc.client.IrcClient;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.message.receive.IrcReceiveChatMessage;
import zm.irc.message.receive.IrcReceiveMessage;
import zm.irc.mqtt.MyMqttClient;

@Service
public class MqttProcessor implements IrcMessageProcessor{
    private static Set<String> MQTT_TARGET_CHANNEL;
    static{
        MQTT_TARGET_CHANNEL = new HashSet<>();
        MQTT_TARGET_CHANNEL.add("#zlang");
    }
    private static final Logger log = Logger.getLogger(MqttProcessor.class);
    @AutoWired
    private MyMqttClient mqttClient;


    public static void addTargetChannel(String channelName){
        MQTT_TARGET_CHANNEL.add(channelName);
    }

    public static void delTargetChannel(String channelName){
        if( !MQTT_TARGET_CHANNEL.contains(channelName)){
            return;
        }
        MQTT_TARGET_CHANNEL.remove(channelName);
    }

    @Override
    public boolean processor(IrcClient client, IrcReceiveMessage receivedMsg) {

        if(receivedMsg instanceof  IrcReceiveChatMessage) {
            IrcReceiveChatMessage chatMsg = (IrcReceiveChatMessage)receivedMsg;
            String channelName = chatMsg.getChannel();
            String fromName = chatMsg.getFromName();
            String simpleChannelName = channelName.replace("#", "");
            if(MQTT_TARGET_CHANNEL.contains(channelName)){
                this.mqttClient.send(simpleChannelName + "[" + fromName + "]: " + chatMsg.getMessageBody());
            }
        }

        return true;
    }
}
